package person.bangbang.im.Androidgin.UI;

import java.util.List;

import person.bangbang.im.Androidgin.AndroidginService;
import person.bangbang.im.Androidgin.R;
import person.bangbang.im.Androidgin.Framework.Account;
import person.bangbang.im.Androidgin.Framework.Buddies;
import person.bangbang.im.Androidgin.Framework.Buddy;
import person.bangbang.im.Androidgin.Framework.Conversation;
import person.bangbang.im.Androidgin.Framework.Conversations;
import person.bangbang.im.Androidgin.Framework.Message;
import person.bangbang.im.Androidgin.Framework.Conversation.OnImEvent;
import person.bangbang.im.Androidgin.Util.Log;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class ChatActivity extends Activity {
	private static String TAG = "Androidgin.UI.ChatActivity";
	
	private ServiceConnection mConn;
	private AndroidginService mService;
	
	private Buddies mBuddies = Buddies.getInstance();
	private Conversations mChats = Conversations.getInstance();
	
	/* the talking buddy */
	private Account mAccount = null;
	private Buddy mBuddy;
	private Buddy _me;
	
	/* a history message we have */
	private TextView mSentView;
	/* the message we want to send to */
	private EditText mImView;
	
	// session message from which the chat begin.
	private String mSessionMessage;
	
	private Conversation mChat;
	private OnImEvent mImEvent = new OnImEvent(){

		public void onRcvdIm(Message m) {
			mImView.setText(mImView.getText().toString() + "\n\n" + format(m));
			/* FIXME
			 * W/System.err(  804): android.view.ViewRoot$CalledFromWrongThreadException: 
			 * Only the original thread that created a view hierarchy can touch its views.
			 *
			 */
			runOnUiThread(new Runnable() {
					public void run() {
//						say("Rcvd a message: " + m.getMessage());
						say("Rcvd a messge: ");
					}
			});

		}

		public void onErrIm(int code, String detail) {
		}

		public void onSentIm(Message msg) {}
	};
	
	private void init(){
		
		try {
			String buddyId;
			buddyId = getIntent().getStringExtra(ContactList.CHAT_BUDDY_ID);
			mBuddy = mBuddies.findBuddyById(buddyId);
			// XXX deal with my specially.
//			_me = mBuddies.findBuddyById("loopback:me");
//			_me = mBuddies.findBuddyById(mBuddy.getAccount().getProtocolID() + ':' + mBuddy.getAccount().getUserName());
			_me = mBuddy.getAccount().getMyself();
			String str = getApplication().getResources().getString(R.string.chat_format_title);
			String title = String.format(str, mBuddy.getUserName());
			setTitle(title);
			
			mAccount = mBuddy.getAccount();
		} catch (NullPointerException e) {
			throw e;
		} finally {
			
		}
		
		Log.d(TAG, "Chat with :" + mBuddy.toString());
		mChat = mChats.getOrNewConversation(mBuddy);
		mChat.regOnImListener(mImEvent);
		((NotificationManager)getSystemService(NOTIFICATION_SERVICE)).cancel(mChat.getNotifyId());
		mService.setCurrentChat(mChat);
		
		mSentView = ((TextView)findViewById(R.id.chat_send_v));
		mImView = ((EditText)findViewById(R.id.chat_im_v));
		
		mSessionMessage = getChatMessages();
		
		mImView.setText(mSessionMessage);
		mSentView.requestFocus();
		
		((Button)findViewById(R.id.chat_send)).setOnClickListener(new View.OnClickListener(){
			public void onClick(View v) {
				sendIm();
			}
		});
		((Button)findViewById(R.id.chat_cancel)).setOnClickListener(new View.OnClickListener(){
			public void onClick(View v) {
				finish();
			}
		});
		setFeatureDrawableResource(Window.FEATURE_RIGHT_ICON, R.drawable.chat);
	}
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		requestWindowFeature(Window.FEATURE_RIGHT_ICON);// must be before setcontentxxxx();
		setContentView(R.layout.chat_relative_1);

			
		mConn = new ServiceConnection(){
			public void onServiceConnected(ComponentName comp, IBinder service) {
				mService = ((AndroidginService.LocalBinder)service).getService();
				
				init();
			}
			public void onServiceDisconnected(ComponentName comp) {}
		};	
		
	}
	@Override
	protected void onResume() {
		super.onResume();
		
		bindService(new Intent(ChatActivity.this, AndroidginService.class), mConn, BIND_AUTO_CREATE);
	}
	@Override
	protected void onPause() {
		super.onPause();
	}
	private void sendIm() {
		if (mSentView.getText().toString().equals("")) {
			say("empty message@@@ what are u dong???");
			return;
		}
		
		String message = mSentView.getText().toString();
		
		mAccount.sendIm(new Message(_me, mBuddy, message));
//		mService.sendIm(new Message(_me, mBuddy, message));
		mSentView.setText("");
		mSentView.requestFocus();
		
		mImView.setSelection(mImView.getText().length());
	}
	
	private String format(Message m) {
		return m.getFrom().getUserName() + ":" + m.getMessage();
	}
	private String getChatMessages(){
		String res = "";
		List<Message> list = mChat.getIMessages();
		
		int len = list.size();
		if (0 == len ) {
			return "";
		}
		for (int i = 0 ; i < len - 1 ; i++) {
			res += format(list.get(i));
			res += "\n\n";
		}
		res += format(list.get(list.size() - 1));
		
		return res;
	}
	private void say(String text) {
		Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
	}
	
	@Override
	public void finish() {
		// TODO Auto-generated method stub
		mService.setCurrentChat(null);
		cleanup();
		super.finish();
	}
	
	private void cleanup() {
		mChat.unRegOnImListener(mImEvent);
		unbindService(mConn);
	}
}
